// manages the retrieval and prasing of data related to the torrents
var UpdateTimer;
var XmlHttp;
var Response;
var JResponse;
var AResponse = new Array();
var NumTorrents;
var OldNumTorrents;
var NumUpdates = 0;
function StartUpdater() {
	UpdateTimer = setInterval(DoUpdateData,5000);
	DoUpdateData();
}

function DoUpdateData(){
	XmlHttp = new XMLHttpRequest;
	XmlHttp.open('GET','http://tor.imageshack.us/tor/?m=1&r=1',true);
	XmlHttp.onreadystatechange = function(){ProcessData();};
	XmlHttp.send(null);
	XmlHttp.close;
}

function ProcessData(){
	if (XmlHttp.readyState != 4) {return false};
	Response = XmlHttp.responseText;
	XmlHttp = null;
	if (Response == "") {return false};
	ParsedObj = JSON.parse(Response);
	ThePayload = ParsedObj.payload;
	NumTorrents = ThePayload.length;
	if (NumUpdates == 12) {
		NumUpdates=0;
		IsFrameLoaded = false;
		ReloadIsFrame();
		return false;
	}
	if (NumTorrents != OldNumTorrents) {
		IsFrameLoaded = false;
		ReloadIsFrame();
		ResetTorrentList();
		OldNumTorrents = NumTorrents;
	}
	if(!IsFrameLoaded) {
		var times = setTimeout(ProcessData,250);
		return false;
	}
	var i = 0;
	for each (Payload in ThePayload) {
		TorrentList[i] = new TorrentItem;
		XferToTorrent(TorrentList[i],Payload);
		if (TorrentList[i].id != undefined) {
			ModifyRow(TorrentList[i]);
		}
		i++;
	}
	NumUpdates+=1;
	return true;
}

function XferToTorrent(Item, TResponse) {
	var StatRegX=new RegExp("<font color=(.*)><b>(.*)</b></font> (\\((.*)%\\))? ?( |Verifying local files|Download Succeeded|Torrent Stopped|Starting\\.\\.\\.|[0-9][0-9]:[0-9][0-9]:[0-9][0-9]:[0-9][0-9]|[0-9][0-9]:[0-9][0-9]:[0-9][0-9]|[0-9][0-9]:[0-9][0-9]|[0-9][0-9])(  \\(Down: (.*) kB\\/s \\| Up: (.*) kB\\/s\\))?");
	var Matches = StatRegX.exec(TResponse.status);
	if (Matches==null) {return(false)};
	/*
	 * mappings 1 = colour 2 = status 4 = percent 5 = eta and status 7 = down
	 * speed 8 = up speed
	 */
	Item.name = GetData(TResponse,1);
	Item.id = TResponse.torrentmeta_id;
	Item.server = TResponse.server;
	var Detail = false;
	if (Matches[2]=="ACTIVE") {
		Item.status=locale("istorclient.tor.active");
		if (Matches[5]=="Verifying local files"||Matches[5]=="Starting..."||Matches[5]=="Download Succeeded") {
			Detail = true;
			Item.eta = "";
			if (Matches[5]=="Verifying local files") {
				Item.status = locale("istorclient.tor.verify");
			} else if (Matches[5]=="Starting...") {
				Item.status = locale("istorclient.tor.starting");
			} else if (Matches[5]=="Download Succeeded") {
				Item.status = locale("istorclient.tor.active");
				Item.eta = locale("istorclient.tor.done") + "+" + locale("istorclient.tor.seed");
			}
		}
	};
	if (Matches[2]=="STOPPED") {Item.status=locale("istorclient.tor.stopped");};
	Item.progress = Matches[4];
	var EtaRegX = new RegExp("[0-9][0-9]:[0-9][0-9]:[0-9][0-9]:[0-9][0-9]|[0-9][0-9]:[0-9][0-9]:[0-9][0-9]|[0-9][0-9]:[0-9][0-9]|[0-9][0-9]");
	if (!Detail) {
		if (Matches[5].match(EtaRegX)) {
			Item.eta = Matches[5];
		} else {
			Item.eta = "";
		};
	};
	Item.down = Matches[7];
	Item.up = Matches[8];
	Item.down ? Item.down = Matches[7] : Item.down = 0;
	Item.up ? Item.up = Matches[8]: Item.up = 0;
	Item.size = parseFloat(GetData(TResponse,2));
	Item.sizeu = GetData(TResponse,3);
	return(true);
}

// included in UpdateManager because it updates an important variable
function SetSelectedTorrent(index) {
	var sel = $(TreeId).currentIndex; // returns -1 if nothing is selected
	var treeItem = $(TreeId).view.getItemAtIndex(sel);
	var ProgressItemLabel = $(treeItem.getAttribute("id")+"-prog").getAttribute("label");
	var selectedId = ProgressItemLabel.split("*")[0];
	var selectedServer = ProgressItemLabel.split("*")[1];
	for each(Item in TorrentList) {
		if (Item.id == selectedId && Item.server == selectedServer) {
			SelectedTorrent = Item;
			return(true);
		}
	}
}
// function called to generate a row from a torrentitem and add it
function AddTorrentRow(Item) {
	// set size downloaded
	Item.sized = (Item.size * (Item.progress / 100)).toFixed(3);
	// create an array of type dataarray
	var TorArray = new Array();
	TorArray[0] = new DataItem(TorBaseId + Item.id + "-stat", Item.status);
	TorArray[1] = new DataItem(TorBaseId + Item.id + "-name", Item.name);
	TorArray[2] = new DataItem(TorBaseId + Item.id + "-eta", Item.eta);
	TorArray[3] = new DataItem(TorBaseId + Item.id + "-prog", Item.progress, "normal");
	TorArray[4] = new DataItem(TorBaseId + Item.id + "-down", Item.down > 0 ? Item.down + " kB/s" : "");
	TorArray[5] = new DataItem(TorBaseId + Item.id + "-up", Item.up > 0 ? Item.up + " kB/s" : "");
	if (Item.status == locale("istorclient.tor.active")) {
		TorArray[6] = new DataItem(TorBaseId + Item.id + "-sized", Item.sized + " " + Item.sizeu);
	} else {
		TorArray[6] = new DataItem(TorBaseId + Item.id + "-sized", "");
	}
	TorArray[7] = new DataItem(TorBaseId + Item.id + "-size", Item.size + " " + Item.sizeu);
	// AddRow treeid,id,dataarray
	TreeManager.AddRow(TreeId, TorBaseId + Item.id, TorArray);
	// Set id and server in label field of progress for later access
	// so i can user getselected on a row and retrieve the selected torrent
	// rether than the row
	$(TorBaseId + Item.id + "-prog").setAttribute("label", Item.id + "*" + Item.server);
}
function ModifyRow(Item) {
	// set size downloaded
	// set the elements
	if ($(TorBaseId + Item.id) != null) {
		$(TorBaseId + Item.id + "-stat").setAttribute("label", Item.status);
		$(TorBaseId + Item.id + "-eta").setAttribute("label", Item.eta);
		$(TorBaseId + Item.id + "-prog").setAttribute("value", Item.progress);
		$(TorBaseId + Item.id + "-prog").setAttribute("label", Item.id + "*" + Item.server);
		$(TorBaseId + Item.id + "-down").setAttribute("label", Item.down > 0 ? Item.down + " kB/s" : "");
		$(TorBaseId + Item.id + "-up").setAttribute("label", Item.up > 0 ? Item.up + " kB/s" : "");
		if (Item.status == locale("istorclient.tor.active")) {
			Item.sized = (Item.size * (Item.progress / 100)).toFixed(3);
			$(TorBaseId + Item.id + "-sized").setAttribute("label", Item.sized + " " + Item.sizeu);
		} else {
			$(TorBaseId + Item.id + "-sized").setAttribute("label", "");
		}
	} else {
		AddTorrentRow(Item);
	}
}
function ResetTorrentList() {
	TorrentList = new Array();
	var element = $(TreeId + "-treechildren");
	while (element.hasChildNodes()) {
		element.removeChild(element.firstChild);
	}
}
function ReloadIsFrame() {
	$('istorclient-isframe').contentDocument.location.href=="about:blank" ? $('istorclient-isframe').contentDocument.location.href="http://tor.imageshack.us/tor/" : $('istorclient-isframe').contentDocument.location.reload();
}
function GetData(TResponse,index) {
	/*
	 * regexp to access content: 1=name 2=numericsize 3=unit var myregexp = new
	 * RegExp("Torrent: (.*) \\(([0-9]*\\.?[0-9]*?) ([K,M,G]B)\\)"); var match =
	 * myregexp.exec(itemstat);
	 */
	var NodeText = GetNode(TResponse);
	var NameRegX = new RegExp("Torrent: (.*) \\(([0-9]*\\.?[0-9]*?) ([K,M,G]B)\\)");
	var Matches = NameRegX.exec(NodeText);
	return(Matches[index]);
}
function GetNode(TResponse) {
	// id.parent.parent.prevsib.prevsib.first.first.nextsib.first.first.first.first.textContent
	// in variables that make no sense, each letter is the initial letter
	// of a node and the variable's letters are in the order of access
	var ifr = document.getElementById('istorclient-isframe');
	var torstat = ifr.contentDocument.getElementById(TResponse.server+"_"+TResponse.torrentmeta_id);
	return(GetNameNode(torstat));
}
